import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);
import { hasToken } from "@/utils/cookie.js";
import { MessageBox } from "element-ui";
const routes = [
  //默认进入login页面
  {
    path: "/",
    redirect: "/login",
  },

  {
    path: "/login",
    name: "login",
    component: () => import("@/views/Login.vue"),
  },

  {
    path: "/register",
    name: "register",
    component: () => import("@/views/Register.vue"),
  },

  {
    path: "/home",
    name: "home",
    component: () => import("@/views/Home.vue"),

    children: [
      {
        path: "",
        redirect: "index",
      },
      {
        path: "index",
        name: "index",
        component: () => import("@/views/child/Index.vue"),
      },
      {
        path: "student",
        name: "student",
        component: () => import("@/views/child/Student.vue"),
      },
      {
        path: "classes",
        name: "classes",
        component: () => import("@/views/child/Classes.vue"),
      },
    ],
  },
];

const router = new VueRouter({
  routes,
});

//导航守卫
//白名单：不需要登录就可以直接通行的页面:登录页和注册页
const whitePageList = ["/login", "/register"];

router.beforeEach((to, from, next) => {
  //判断是否有登录，通过是否存有token来判断
  if (hasToken()) {
    //有登录,放行
    whitePageList.includes(to.path)?next("/home/index"):next()
  } else {
    //未登录且在白名单内，放行
    if (whitePageList.includes(to.path)) {
      next();
    } else {
      //未登录且不在白名单内，要去到登录页
      MessageBox.confirm("您未登录，请先登录！", "提示", {
        type: "warning",
      })
        .then(() => {
          //点击确定的
          next("/login");
        })
        .catch(() => {
          //点击取消的
          next("/login");
        });
    }
  }
});

export default router;
